# -*- coding: utf-8 -*-
# 版权所有 (c) [王广旭]
# 本程序由王广旭开发，保留所有权利。
# 严禁将本程序以任何形式用于商业用途。
# 非商业使用需遵循以下条件：
# - 不得删除或修改此版权声明。
# - 若对程序进行再分发，需包含此版权声明。

import subprocess
import sys
import time
import win32serviceutil
import win32api
import win32con


class Licensee:
    _instance = None

    def __new__(cls):
        if cls._instance is None:
            # 创建新的实例
            instance = super().__new__(cls)
            cls._instance = instance
            # print("Licensee::__new__")
        return cls._instance

    def __init__(self):
        # 判断实例是否已经初始化
        if not hasattr(self, 'authorization_time'):
            # print("Licensee::__init__")
            self.authorization_time = [2025, 2, 10, 19, 52, 37]
            self._break_program()
            self.is_provide_demo = self.provide_demo()

    def _break_program(self):
        if self.over_time():
            print("有效期：{}-{}-{} {}:{}:{}".format(self.authorization_time[0], self.authorization_time[1],
                                                 self.authorization_time[2],self.authorization_time[3],
                                                 self.authorization_time[4], self.authorization_time[5]))
            print("当前演示版本授权已过期")
            input("按回车键退出程序...")
            sys.exit(0)

    def provide_demo(self):
        print("\n****************************************************************\n")
        if self.check_network_windows() and self.check_auto_time_windows():
            print("使用有效期：{}-{}-{} {}:{}:{}".format(self.authorization_time[0], self.authorization_time[1],
                                                   self.authorization_time[2], self.authorization_time[3],
                                                   self.authorization_time[4], self.authorization_time[5]))
            print("\n****************************************************************\n")
            return False
        else:
            print("当前电脑网络异常或者时间未设置为自动获取，当前仅提供演示，无实际操作")
            print("如需实际操作，请连接网络、设置自动获取时间")
            print("windows已设置自动获取时间可能无效，需要重新启动自动获取，同步网络时间")
            print("使用有效期：{}-{}-{} {}:{}:{}".format(self.authorization_time[0], self.authorization_time[1],
                                                   self.authorization_time[2], self.authorization_time[3],
                                                   self.authorization_time[4], self.authorization_time[5]))
            print("\n****************************************************************\n")
            input("按回车键继续...\n")
            return True

    def check_auto_time_windows(self):
        try:
            # 获取 w32time 服务的状态
            service_status = win32serviceutil.QueryServiceStatus('w32time')
            # 服务状态为 4 表示正在运行
            if service_status[1] == 4:
                # 进一步检查配置信息
                hkey = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE,
                                           r"SYSTEM\CurrentControlSet\Services\w32time\Parameters")
                value, type_ = win32api.RegQueryValueEx(hkey, "Type")
                win32api.RegCloseKey(hkey)
                # Type 值为 NTP 表示使用网络时间协议，即自动时间同步
                if value == "NTP":
                    print("Windows 系统已启用自动获取时间。")
                    return True
                else:
                    print("Windows 系统未启用自动获取时间。")
                    return False
            else:
                print("Windows 系统未启用自动获取时间。")
                return False
        except Exception as e:
            print(f"发生错误: {e}")
            return False

    def check_network_windows(self):
        try:
            result = subprocess.run(["ping", "-n", "1", "www.baidu.com"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=5)
            if result.returncode == 0:
                print("网络连接正常。")
                return True
            else:
                print("ping www.baidu.com 命令超时，网络连接可能存在问题。")
                return False
        except subprocess.TimeoutExpired:
            print("ping www.baidu.com 命令超时，网络连接可能存在问题。")
            return False

    def over_time(self):
        time_tuple = time.localtime(time.time())
        if self.authorization_time[0] > time_tuple[0]:
            return False
        elif self.authorization_time[0] == time_tuple[0]:
            if self.authorization_time[1] > time_tuple[1]:
                return False
            elif self.authorization_time[1] == time_tuple[1]:
                if self.authorization_time[2] > time_tuple[2]:
                    return False
                elif self.authorization_time[2] == time_tuple[2]:
                    if self.authorization_time[3] > time_tuple[3]:
                        return False
                    elif self.authorization_time[3] == time_tuple[3]:
                        if self.authorization_time[4] > time_tuple[4]:
                            return False
                        elif self.authorization_time[4] == time_tuple[4]:
                            if self.authorization_time[5] > time_tuple[5]:
                                return False
        return True


